﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.UI.EM.Views.Interfaces;
using Common.Model;
using Microsoft.Practices.Composite.Presentation.Commands;
using Microsoft.Practices.Composite.Events;
using Common.Services;
using System.Data.Objects.DataClasses;

namespace Common.UI.EM.Views
{
    public class FilterPresentationModel<S, E, C, EV> : IFilterPresentationModel<S, E, C, EV>
        where S : IGenericEntityManagerService<E, C, EV>, new()
        where E : EntityObject
        where C : CriteriaEntity
        where EV : ViewEntity
    {

        public event SearchCalledEventHandler SearchCalled;

        public IFilterView View
        {
            get;
            set;
        }

        public DelegateCommand<Object> SearchCommand
        {
            get;
            set;
        }

        public C CriteriaEntity { get; set; }

        public FilterPresentationModel(IFilterView view)
        {
            this.View = view;
            this.View.Model = this;

            this.AddCommands();
        }

        private void AddCommands()
        {
            this.SearchCommand = new DelegateCommand<object>(ExecuteSearchCommand, CanExecuteSearchCommand);
            this.AddCustomCommands();
        }

        protected virtual void AddCustomCommands()
        {

        }


        private void ExecuteSearchCommand(Object arg)
        {
            if (this.Validate() && SearchCalled != null)
            {
                SearchCalled(this, new DataEventArgs<CriteriaEntity>(this.CriteriaEntity));
            }
        }

        private bool Validate()
        {
            return this.View.Validate();
        }

        private Boolean CanExecuteSearchCommand(Object arg)
        {
            return true;
        }


        public void LoadCriteria(C criteriaEntity)
        {
            CriteriaEntity = criteriaEntity;
        }

    }
}